/*
 * Thread.cpp
 *
 *  Created on: Mar 24, 2011
 *      Author: stud
 */
#include "linuxwrap.h"
#include <cstdio>
#include <cstdlib>

//-------------------------------
// CLASS: Thread
//-------------------------------
Thread::Thread(Thread::ThreadPriority pri, std::string nme) : priority(pri), name(nme), rootMode(true)
{
	if(geteuid()!=0)
	{
		printf("You must have admin rights to use class Thread. Rerun program as root\n");
		exit(1);
	}

}

Thread::~Thread() {}

void Thread::start()
{
	pthread_attr_t attr;
	sched_param sched_p;

	pthread_attr_init(&attr);										// Init attr
	if (rootMode)
	{
		pthread_attr_setschedpolicy(&attr, SCHED_RR);					// Set RR scheduling (RT, timesliced)
		pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);	// Create thread with explicit (non-inherited) scheduling - setting priority will not work otherwise!
		sched_p.sched_priority = (int)priority;							// Set priority
		pthread_attr_setschedparam(&attr, &sched_p);					// Use the priority
	}
	if ((errno = pthread_create(&threadId, &attr, threadMapper, (void*)this)) != 0)
	{
		linuxwrap::reportError("Thread start");
		exit(1);
	}
}

void* Thread::threadMapper(void* p)
{
	((Thread*)p)->run();
	return 0;
}

bool Thread::setPriority(Thread::ThreadPriority prio)
{
	priority = prio;
	if ((errno = pthread_setschedprio(threadId, prio)) == 0)
	        return true;
	linuxwrap::reportError("Thread setPriority");
	return false;
}

Thread::ThreadPriority Thread::getPriority()
{
	return priority;
}

std::string Thread::getName()
{
	return name;
}
